<?php

function database_get_entity($table) {
  $query  = "SHOW COLUMNS FROM `$table`";
  $data   = database_get_assoc($query);
  $entity = array();
  
  foreach ($data as $field) {
    $entity[$field['Field']] = '';  
  }
  
  return $entity;
}

function database_remove($table, $id) {
  $query  = "DELETE FROM `$table` WHERE `id` = $id";
  $result = database_query($query); 
}

function database_query($query) {
  $result = mysql_query($query);
  
  if (!$result) {
    echo $query;
    throw new Exception(mysql_error());    
  }
  
  return $result;
}

function database_get_by_id($table, $id) {
    
  $query  = "SELECT * FROM `$table` WHERE `id` = $id";
  $result = database_get_assoc($query);
  return $result[0];
}

function database_get_assoc($query) {
    
  $result = database_query($query);
  $data   = array();
  
  while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row;    
  }
  
  return $data;
}

function database_insert($table, $data) {
  
  $fields = array_keys($data);
  $values = array_values($data);
  
  $fieldsStr = '`' . implode('`, `', $fields) . '`';
  $valuesStr = "'" . implode("', '", $values) . "'";
  
  $query = "INSERT INTO `$table` ($fieldsStr) VALUES($valuesStr)";
  database_query($query);
  
  return mysql_insert_id();
}

function database_replace($table, $data) {
  
  $fields = array_keys($data);
  $values = array_values($data);
  
  $fieldsStr = '`' . implode('`, `', $fields) . '`';
  $valuesStr = "'" . implode("', '", $values) . "'";
  
  $query = "REPLACE INTO `$table` ($fieldsStr) VALUES($valuesStr)";
  database_query($query);
  
  return mysql_insert_id();
}
